<?php
/**
 * Memcache缓存类
 */
class MemcacheCache extends CacheHelper
{
	/**
     * 操作句柄
     * @var string
     * @access protected
     */
    protected $handler;

	/**
     * 数据缓存沲
     *
     * @var Array
     */
    public static $data = array();

    /**
     * 架构函数
     * @access public
     */
    public function __construct($options = array())
    {
        if ( !extension_loaded('memcache') ) throw new YucyException('您的运行环境不支持'.':memcache');
        
        if(empty($options))
        {
            $options = array(array
            (
                'host'  => '127.0.0.1',
                'port'  => 11211,
                'timeout' => 60,
            ));
        }
       
        $this->handler  = new Memcache;
        
        $this->type = 'Memcache';
        
    	foreach ($options as $m)
    	{
    	    $this->handler->addServer($m['host'], $m['port']);
    	}
    }

    /**
     * 是否连接
     * @access private
     * @return boolen
     */
    private function isConnected()
    {
        return $this->connected;
    }

    
    /**
     * 读取缓存
     * @access public
     * @param string $key 缓存变量名
     * @return mixed
     */
    public function get($key)
    {
		$this->Q(1);
    	$key = (empty($this->prefix)) ? $key : $this->prefix . $key;
		
		if (is_array($key))
		{
			$v_data = $k_data = array();
			foreach ($key as $v)
			{
				if (array_key_exists($v, self::$data))
					$v_data[$v] = self::$data[$v];
				else 
					$k_data[] = $v;			
			}
			
			if (count($k_data) > 0)
			{
				$k_data = $this->handler->get($k_data);
				if (is_array($k_data) && count($k_data) > 0)
				{
					$v_data = array_merge($v_data, $k_data);			//合并到返回数组
					self::$data = array_merge(self::$data, $k_data);	//合并到缓存数组					
				}
			}
			
			return $v_data;
		}
		else 
		{
			if (!array_key_exists($key, self::$data))
				self::$data[$key] = $this->handler->get($key);
				
			return self::$data[$key];	
		}
    }

    
    /**
     * 写入缓存
     * @access public
     * @param string $key 缓存变量名
     * @param mixed $value  存储数据
     * @return boolen
     */
    public function set($key, $value, $expire = 0, $flag = 0)
    {
		$this->W(1);
		$key = $this->prefix . $key;
		$expire = (int)$expire;
            
        self::$data[$key] = $value;
        return $this->handler->set($key, $value, $flag, $expire);
    }

    
    /**
     * 删除缓存
     *
     * @access public
     * @param string $key 缓存变量名
     * @return boolen
     */
    public function delete($key)
    {
        if (array_key_exists($key, self::$data))
			unset(self::$data[$key]);
			
		return $this->handler->delete($this->prefix . $key);
    }
    

    
    /**
     * 清除缓存
     * @access public
     * @return boolen
     */
    public function clear()
    {
        return $this->handler->flush();
    }
}